/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.order.web.serviceorder;

import com.jeesite.common.collect.ListUtils;
import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.lang.NumberUtils;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.agreement.entity.supplychainserviceagreement.SupplyChainServiceAgreement;
import com.jeesite.modules.agreement.entity.yearcarsalepurchaseagreement.YearCarSalePurchaseAgreement;
import com.jeesite.modules.agreement.service.supplychainserviceagreement.SupplyChainServiceAgreementService;
import com.jeesite.modules.agreement.service.yearcarsalepurchaseagreement.YearCarSalePurchaseAgreementService;
import com.jeesite.modules.ar.dao.TarDetailDao;
import com.jeesite.modules.ar.entity.Tar;
import com.jeesite.modules.ar.entity.TarDetail;
import com.jeesite.modules.ar.service.TarService;
import com.jeesite.modules.base.dao.investorfinancialinfo.LcFinancialRatioDao;
import com.jeesite.modules.base.dao.investorfinancialinfo.TtFinancialRatioDao;
import com.jeesite.modules.base.entity.cars.Tcar;
import com.jeesite.modules.base.entity.customer.Customer;
import com.jeesite.modules.base.entity.fixedexpense.FixedExpense;
import com.jeesite.modules.base.entity.fixedexpense.LadderPrice;
import com.jeesite.modules.base.entity.investorfinancialinfo.InvestorFinancialInfo;
import com.jeesite.modules.base.entity.investorfinancialinfo.LcFinancialRatio;
import com.jeesite.modules.base.entity.investorfinancialinfo.TtFinancialRatio;
import com.jeesite.modules.base.entity.supplier.Supplier;
import com.jeesite.modules.base.service.cars.TcarService;
import com.jeesite.modules.base.service.customer.CustomerService;
import com.jeesite.modules.base.service.fixedexpense.FixedExpenseService;
import com.jeesite.modules.base.service.investorfinancialinfo.InvestorFinancialInfoService;
import com.jeesite.modules.base.service.supplier.SupplierService;
import com.jeesite.modules.custom.enumInfo.AccountType;
import com.jeesite.modules.custom.enumInfo.departmentEnum;
import com.jeesite.modules.custom.enumInfo.supplierTypeEnum;
import com.jeesite.modules.custom.service.CodeRuleService;
import com.jeesite.modules.financial.entity.lettercredit.LetterCredit;
import com.jeesite.modules.financial.service.lettercredit.LetterCreditService;
import com.jeesite.modules.order.entity.serviceorder.RelatedRecord;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrder;
import com.jeesite.modules.order.entity.serviceorder.ServiceOrderDetail;
import com.jeesite.modules.order.service.serviceorder.ServiceOrderService;
import com.jeesite.modules.payment.entity.Tap;
import com.jeesite.modules.payment.entity.TapDetail;
import com.jeesite.modules.payment.service.TapService;
import com.jeesite.modules.prepay.entity.Tprepayment;
import com.jeesite.modules.prepay.entity.TprepaymentEstimated;
import com.jeesite.modules.prepay.service.TprepaymentService;
import com.jeesite.modules.prerecieve.entity.TadvancesReceived;
import com.jeesite.modules.prerecieve.entity.TadvancesReceivedEstimated;
import com.jeesite.modules.prerecieve.service.TadvancesReceivedService;
import com.jeesite.modules.sys.entity.Company;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.CompanyService;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.sys.utils.EmpUtils;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 服务订单Controller
 *
 * @author Kilo
 * @version 2021-03-05
 */
@Controller
@RequestMapping(value = "${adminPath}/order/serviceorder/serviceOrder")
public class ServiceOrderController extends BaseController {

    @Autowired
    private ServiceOrderService serviceOrderService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private SupplyChainServiceAgreementService supplyChainServiceAgreementService;
    @Autowired
    private YearCarSalePurchaseAgreementService yearCarSalePurchaseAgreementService;
    @Autowired
    private InvestorFinancialInfoService investorFinancialInfoService;
    @Autowired
    private LcFinancialRatioDao lcFinancialRatioDao;
    @Autowired
    private TtFinancialRatioDao ttFinancialRatioDao;
    @Autowired
    private TcarService tcarService;
    @Autowired
    private CodeRuleService codeRuleService;
    @Autowired
    private EmpUserService empUserService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private LetterCreditService letterCreditService;
    @Autowired
    private TadvancesReceivedService tadvancesReceivedService;
    @Autowired
    private TprepaymentService tprepaymentService;
    @Autowired
    private FixedExpenseService fixedExpenseService;
    @Autowired
    private TapService tapService;
    @Autowired
    private TarService tarService;
    @Autowired
    private TarDetailDao  tarDetailDao;

    /**
     * 获取数据
     */
    @ModelAttribute
    public ServiceOrder get(String serviceOrderId, boolean isNewRecord) {
        return serviceOrderService.get(serviceOrderId, isNewRecord);
    }

    /**
     * 查询列表
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = {"list", ""})
    public String list(ServiceOrder serviceOrder, Model model) {
        model.addAttribute("serviceOrder", serviceOrder);
        // 供应商
        List<Supplier> supplierList = supplierService.findList(new Supplier());
        model.addAttribute("supplierList", supplierList);
        // 海外资方
        Supplier hwzf = new Supplier();
        hwzf.setSupplierType("2");
        List<Supplier> hwzfList = supplierService.findList(hwzf);
        // 供货外商
        Supplier ghws = new Supplier();
        ghws.setSupplierType("3");
        List<Supplier> ghwsList = supplierService.findList(ghws);
        hwzfList.addAll(ghwsList);
        model.addAttribute("hwzfList", hwzfList);
        // 国内资方
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType("1");
        List<Supplier> gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);
        // 车辆
        List<Tcar> tcarList = tcarService.findList(new Tcar());
        Tcar tcar = new Tcar();
        tcar.setCarName("");
        tcar.setCarId("");
        tcarList.add(tcar);
        model.addAttribute("tcarList", tcarList);
        model.addAttribute("listUser", empUserService.findList(new EmpUser()));
        return "modules/order/serviceorder/serviceOrderList";
    }

    /**
     * 查询列表数据
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = "listData")
    @ResponseBody
    public Page<ServiceOrder> listData(ServiceOrder serviceOrder, HttpServletRequest request, HttpServletResponse response) {
        serviceOrder.setPage(new Page<>(request, response));
        Page<ServiceOrder> page = serviceOrderService.findPage(serviceOrder);
        return page;
    }

    /**
     * 查看编辑表单
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = "form")
    public String form(ServiceOrder serviceOrder, Model model) {
        if (serviceOrder.getIsNewRecord()) {
            Company com = companyService.get(EmpUtils.getEmployee().getCompany());
            serviceOrder.setCompany(com);
            serviceOrder.setOrderStatus("1");
            serviceOrder.setApproveStatus("1");
        }
        model.addAttribute("serviceOrder", serviceOrder);
        // 供应商
        List<Supplier> supplierList = supplierService.findList(new Supplier());
        model.addAttribute("supplierList", supplierList);
        // 海外资方
        Supplier hwzf = new Supplier();
        hwzf.setSupplierType(supplierTypeEnum.FOR_SUPPLIER.getCode());
        List<Supplier> hwzfList = supplierService.findList(hwzf);
        // 供货外商
        Supplier ghws = new Supplier();
        ghws.setSupplierType(supplierTypeEnum.SUPPLIER.getCode());
        List<Supplier> ghwsList = supplierService.findList(ghws);
        model.addAttribute("ghwsList", ghwsList);
        hwzfList.addAll(ghwsList);
        model.addAttribute("hwzfList", hwzfList);
        // 国内资方
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType(supplierTypeEnum.IN_SUPPLIER.getCode());
        List<Supplier> gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);
        //客户
        List<Customer> customerList = customerService.findList(new Customer());
        model.addAttribute("customerList",customerList);
        // 车辆
        List<Tcar> tcarList = tcarService.findList(new Tcar());
        Tcar tcar = new Tcar();
        tcar.setCarName("");
        tcar.setCarId("");
        tcarList.add(tcar);
        model.addAttribute("tcarList", tcarList);
        model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));// 信用证
        return "modules/order/serviceorder/serviceOrderForm";
    }

    /**
     * 查看表单详情
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = "detail")
    public String detail(ServiceOrder serviceOrder, Model model) {
        // 明细行合计
        Double totalAmount = 0D;
        Double totalAgencyFee = 0D;
        Double totalRiskMargin = 0D;
        Double totalPrePay = 0D;
        Double totalCost = 0D;
        Integer overseasWarehouseCount = 0;

        for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
            totalAmount = NumberUtils.add(totalAmount, serviceOrderDetail.getAmount());
            totalAgencyFee = NumberUtils.add(totalAgencyFee, serviceOrderDetail.getAgencyFee());
            totalRiskMargin = NumberUtils.add(totalRiskMargin, serviceOrderDetail.getRiskMargin());
            totalPrePay = NumberUtils.add(totalPrePay, serviceOrderDetail.getPrePay());
            totalCost = NumberUtils.add(totalCost, serviceOrderDetail.getTotalCost());
            if (StringUtils.isNotEmpty(serviceOrderDetail.getOverseasWarehouseId())) {
                overseasWarehouseCount++;
            }
        }
        serviceOrder.setTotalAmount(totalAmount);
        serviceOrder.setTotalAgencyFee(totalAgencyFee);
        serviceOrder.setTotalRiskMargin(totalRiskMargin);
        serviceOrder.setTotalPrePay(totalPrePay);
        serviceOrder.setTotalCost(totalCost);
        Boolean overseasWarehouseCode = false; // 海外仓验证
        Boolean arrivalReminderCode = false; // 导弹提醒验证
        if (overseasWarehouseCount != 0){
            arrivalReminderCode = true;
        }
        if (overseasWarehouseCount < serviceOrder.getServiceOrderDetailList().size()) {
            overseasWarehouseCode = true;
        }
        serviceOrder.setOverseasWarehouseCode(overseasWarehouseCode);
        serviceOrder.setArrivalReminderCode(arrivalReminderCode);

        // 相关记录
        List<RelatedRecord> relatedRecordList = ListUtils.newArrayList();

        List<Map<String,Object>> relatedinfoList = tarDetailDao.findRelationInfoByServiceOrderId(serviceOrder.getServiceOrderId());
        String type = null;
        for(Map<String,Object> relatedInfoMap:relatedinfoList){
            RelatedRecord relatedRecord = new RelatedRecord();
            relatedRecord.setBillCode(String.valueOf(relatedInfoMap.get("code")));
            relatedRecord.setDate((Date) relatedInfoMap.get("date"));
            relatedRecord.setExpenseItem(String.valueOf(relatedInfoMap.get("name")));
            type = String.valueOf(relatedInfoMap.get("type"));
            switch (type){
                case "ar":
                    relatedRecord.setYingshouAmount(((BigDecimal)relatedInfoMap.get("amount")).doubleValue());
                    break;
                case "ap":
                    relatedRecord.setYingfuAmount(((BigDecimal)relatedInfoMap.get("amount")).doubleValue());
                    break;
                case "receivable":
                    relatedRecord.setShishouAmount(((BigDecimal)relatedInfoMap.get("amount")).doubleValue());
                    break;
                case "payment":
                    relatedRecord.setShifuAmount(((BigDecimal)relatedInfoMap.get("amount")).doubleValue());
                    break;
                case "received":
                    relatedRecord.setYushouAmount(((BigDecimal)relatedInfoMap.get("amount")).doubleValue());
                    break;
                case "prepayment":
                    relatedRecord.setYufuAmount(((BigDecimal)relatedInfoMap.get("amount")).doubleValue());
                    break;
                default:
            }
            relatedRecordList.add(relatedRecord);
        }

        // 应收单
        /*Tar tar = new Tar();
        tar.setServiceOrderId(serviceOrder.getServiceOrderId());
        List<Tar> list = tarService.findList(tar);
        for (Tar tar1 : list) {
            for (TarDetail tarDetail : tarService.get(tar1).getTarDetailList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tar1.getArCode());
                relatedRecord.setDate(tar1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tarDetail.getExpenseItem()).getFixedExpenseName());
                relatedRecord.setYingshouAmount(tarDetail.getApAmount());
                relatedRecordList.add(relatedRecord);
            }
        }

        // 应付单
        Tap tap = new Tap();
        tap.setServiceOrderId(serviceOrder.getServiceOrderId());
        List<Tap> list1 = tapService.findList(tap);
        for (Tap tap1 : list1) {
            for (TapDetail tapDetail : tapService.get(tap1).getTapDetailList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tap1.getApCode());
                relatedRecord.setDate(tap1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tapDetail.getExpenseItem()).getFixedExpenseName());
                relatedRecord.setYingfuAmount(tapDetail.getApAmount());
                relatedRecordList.add(relatedRecord);
            }
        }

        // 实收单
        Treceivable treceivable = new Treceivable();
        treceivable.setServiceOrderId(serviceOrder.getServiceOrderId());
        List<Treceivable> list2 = treceivableService.findList(treceivable);
        for (Treceivable treceivable1 : list2) {
            for (TreceivableDetail treceivableDetail : treceivableService.get(treceivable1).getTreceivableDetailList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(treceivable1.getReceivableCode());
                relatedRecord.setDate(treceivable1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(treceivableDetail.getExpenseItem()).getFixedExpenseName());
                relatedRecord.setShishouAmount(treceivableDetail.getActualArAmount());
                relatedRecordList.add(relatedRecord);
            }
        }

        // 实付单
        Tpayment tpayment = new Tpayment();
        tpayment.setServiceOrderId(serviceOrder.getServiceOrderId());
        List<Tpayment> list3 = tpaymentService.findList(tpayment);
        for (Tpayment tpayment1 : list3) {
            for (TpaymentDetail tpaymentDetail : tpaymentService.get(tpayment1).getTpaymentDetailList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tpayment1.getPaymentCode());
                relatedRecord.setDate(tpayment1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tpaymentDetail.getExpenseItem()).getFixedExpenseName());
                relatedRecord.setShifuAmount(tpaymentDetail.getActualApAmount());
                relatedRecordList.add(relatedRecord);
            }
        }
        // 预收单
        TadvancesReceived tadvancesReceived = new TadvancesReceived();
        tadvancesReceived.setServiceOrderId(serviceOrder.getServiceOrderId());
        List<TadvancesReceived> list4 = tadvancesReceivedService.findList(tadvancesReceived);
        for (TadvancesReceived tadvancesReceived1 : list4) {
            for (TadvancesReceivedEstimated tadvancesReceivedEstimated : tadvancesReceivedService.get(tadvancesReceived1).getTadvancesReceivedEstimatedList()) {
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tadvancesReceived1.getAdvancesReceivedCode());
                relatedRecord.setDate(tadvancesReceived1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tadvancesReceivedEstimated.getAdvancesReceivedType()).getFixedExpenseName());
                relatedRecord.setYushouAmount(tadvancesReceivedEstimated.getEstimatedReceivedAmount());
                relatedRecordList.add(relatedRecord);
            }
        }
        // 预付单
        Tprepayment tprepayment=new Tprepayment();
        tprepayment.setServiceOrderId(serviceOrder.getServiceOrderId());
        List<Tprepayment> list5=tprepaymentService.findList(tprepayment);
        for (Tprepayment tprepayment1 : list5){
            for (TprepaymentEstimated tprepaymentEstimated :tprepaymentService.get(tprepayment1).getTprepaymentEstimatedList()){
                RelatedRecord relatedRecord = new RelatedRecord();
                relatedRecord.setBillCode(tprepayment1.getPrepaymentCode());
                relatedRecord.setDate(tprepayment1.getDate());
                relatedRecord.setExpenseItem(fixedExpenseService.get(tprepaymentEstimated.getFixedExpense()).getFixedExpenseName());
                relatedRecord.setYufuAmount(tprepaymentEstimated.getEstimatedPaymentAmount());
                relatedRecordList.add(relatedRecord);
            }
        }*/

        serviceOrder.setRelatedRecordList(relatedRecordList);

        model.addAttribute("serviceOrder", serviceOrder);
        // 供应商
        List<Supplier> supplierList = supplierService.findList(new Supplier());
        model.addAttribute("supplierList", supplierList);
        // 海外资方
        Supplier hwzf = new Supplier();
        hwzf.setSupplierType(supplierTypeEnum.FOR_SUPPLIER.getCode());
        List<Supplier> hwzfList = supplierService.findList(hwzf);
        // 供货外商
        Supplier ghws = new Supplier();
        ghws.setSupplierType(supplierTypeEnum.SUPPLIER.getCode());
        List<Supplier> ghwsList = supplierService.findList(ghws);
        model.addAttribute("ghwsList", ghwsList);
        hwzfList.addAll(ghwsList);
        model.addAttribute("hwzfList", hwzfList);
        // 国内资方
        Supplier gnzf = new Supplier();
        gnzf.setSupplierType(supplierTypeEnum.IN_SUPPLIER.getCode());
        List<Supplier> gnzfList = supplierService.findList(gnzf);
        model.addAttribute("gnzfList", gnzfList);
        //客户
        List<Customer> customerList = customerService.findList(new Customer());
        model.addAttribute("customerList",customerList);
        // 车辆
        List<Tcar> tcarList = tcarService.findList(new Tcar());
        Tcar tcar = new Tcar();
        tcar.setCarName("");
        tcar.setCarId("");
        tcarList.add(tcar);
        model.addAttribute("tcarList", tcarList);
        model.addAttribute("listLetterCredit", letterCreditService.findList(new LetterCredit()));// 信用证
        return "modules/order/serviceorder/serviceOrderDetail";
    }

    /**
     * 保存数据
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:edit")
    @PostMapping(value = "save")
    @ResponseBody
    @Transactional(readOnly = false)
    public String save(@Validated ServiceOrder serviceOrder) {
        if (serviceOrder.getIsNewRecord()) {
            serviceOrder.setServiceOrderCode(codeRuleService.getCode("ServiceOrder"));
            // 汽车买卖合同号
            ServiceOrder so = new ServiceOrder();
            so.setInvestorId(serviceOrder.getInvestorId());
            String prefix = supplierService.get(serviceOrder.getInvestorId()).getSupplierNameAbbreviation();
            String year = DateUtils.getYear();
            String month = DateUtils.getMonth();
            List<ServiceOrder> list = serviceOrderService.findList(so);
            int contractNumberCurrentNumber = 1;
            if (ListUtils.isNotEmpty(list)) {
                contractNumberCurrentNumber = list.stream().filter(s -> StringUtils.isNotEmpty(s.getContractNumber())
                        && (year.substring(year.length() - 2) + month).equals(s.getContractNumber().substring(4, 8)))
                        .mapToInt(ServiceOrder -> Integer.parseInt(ServiceOrder.getContractNumber().substring(8))).max().getAsInt() + 1;
            }
            String contractNumber = prefix + year.substring(year.length() - 2) + month + String.format("%0" + 4 + "d", contractNumberCurrentNumber);
            serviceOrder.setContractNumber(contractNumber);
            // 采购委托书号
           ServiceOrder sos = new ServiceOrder();
           sos.setCustomer(serviceOrder.getCustomer());
            String customerPrefix = customerService.get(serviceOrder.getCustomerId()).getCustomerNameAbbreviation();
            List<ServiceOrder> soList = serviceOrderService.findList(sos);
            int purchaseCommissionNumberCurrentNumber = 1;
            if (ListUtils.isNotEmpty(soList)) {
                purchaseCommissionNumberCurrentNumber = soList.stream().filter(s -> StringUtils.isNotEmpty(s.getPurchaseCommissionNumber())
                        && (year.substring(year.length() - 2) + month).equals(s.getPurchaseCommissionNumber().substring(4, 8)))
                        .mapToInt(ServiceOrder -> Integer.parseInt(ServiceOrder.getPurchaseCommissionNumber().substring(8))).max().getAsInt() + 1;
            }
            String purchaseCommissionNumber = customerPrefix + year.substring(year.length() - 2) + month + String.format("%0" + 4 + "d", purchaseCommissionNumberCurrentNumber);
            serviceOrder.setPurchaseCommissionNumber(purchaseCommissionNumber);
            serviceOrder.setCreateBy(UserUtils.getUser().getLoginCode());
            serviceOrder.setVersion(1L);
        }
        serviceOrderService.save(serviceOrder);
        if (serviceOrder.getIsNewRecord()) {
            codeRuleService.updateCurrentNumber("ServiceOrder");
        }
        return renderResult(Global.TRUE, text("保存服务订单成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:edit")
    @RequestMapping(value = "delete")
    @ResponseBody
    public String delete(ServiceOrder serviceOrder) {
        serviceOrderService.delete(serviceOrder);
        return renderResult(Global.TRUE, text("删除服务订单成功！"));
    }

    /**
     * 删除数据
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = "getOneByIdAndExpend")
    @ResponseBody
    public ServiceOrder getOneByIdAndExpend(@RequestParam("serviceOrderId") String serviceOrderId,@RequestParam("expenseItem") String expenseItem) {
        ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
        FixedExpense fixedExpense = fixedExpenseService.get(expenseItem);
        // 物流完结锁定后的车架号，不能做物流部门对应的固定费用类型的收支明细单
        List<ServiceOrderDetail> listServiceOrderDetail = ListUtils.newArrayList();
        if (fixedExpense.getOffice() != null && departmentEnum.LOGISTICS.getCode().equals(fixedExpense.getOffice().getOfficeCode())){
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                if ("0".equals(serviceOrderDetail.getLockFlag())){
                    listServiceOrderDetail.add(serviceOrderDetail);
                }
            }
            serviceOrder.setServiceOrderDetailList(listServiceOrderDetail);
        }
        return serviceOrder;
    }

    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = "getOneById")
    @ResponseBody
    public ServiceOrder getOneById(@RequestParam("serviceOrderId") String serviceOrderId) {
        return serviceOrderService.get(serviceOrderId);
    }

    /**
     * 获取供应链服务协议
     *
     * @param customerId
     */
    @RequestMapping(value = "getSupplyChainServiceAgreement")
    @ResponseBody
    public String getSupplyChainServiceAgreement(@RequestParam("customerId") String customerId,@RequestParam("date") Date date) throws ParseException {
        SupplyChainServiceAgreement supplyChainServiceAgreement = new SupplyChainServiceAgreement();
        Customer customer = new Customer();
        customer.setCustomerId(customerId);
        supplyChainServiceAgreement.setCustomer(customer);
        supplyChainServiceAgreement.setStatus1("1");
        List<SupplyChainServiceAgreement> list = supplyChainServiceAgreementService.findList(supplyChainServiceAgreement);
        for (SupplyChainServiceAgreement chainServiceAgreement : list) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (date.compareTo(chainServiceAgreement.getStartDate()) >= 0 && date.compareTo(chainServiceAgreement.getEndDate()) <= 0) {
                return chainServiceAgreement.getSupplyChainServiceAgreementCode();
            }
        }
        return "";
    }

    /**
     * 获取年度汽车买卖协议
     *
     * @param supplierId
     */
    @RequestMapping(value = "getYearCarSalePurchaseAgreement")
    @ResponseBody
    public String getYearCarSalePurchaseAgreement(@RequestParam("supplierId") String supplierId,@RequestParam("date") Date date) throws ParseException {
        YearCarSalePurchaseAgreement yearCarSalePurchaseAgreement = new YearCarSalePurchaseAgreement();
        Supplier supplier = new Supplier();
        supplier.setSupplierId(supplierId);
        yearCarSalePurchaseAgreement.setSupplier(supplier);
        yearCarSalePurchaseAgreement.setStatus1("1");
        List<YearCarSalePurchaseAgreement> list = yearCarSalePurchaseAgreementService.findList(yearCarSalePurchaseAgreement);
        for (YearCarSalePurchaseAgreement yearCarSalePurchaseAgreement1 : list) {
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            if (date.compareTo(yearCarSalePurchaseAgreement1.getStartDate()) >= 0 && date.compareTo(yearCarSalePurchaseAgreement1.getEndDate()) <= 0) {
                return yearCarSalePurchaseAgreement1.getYearCarSalePurchaseAgreementCode();
            }
        }
        return "";
    }

    /**
     * 获取保证金、费用比例列表
     *
     * @param supplierId
     */
    @RequestMapping(value = "getList")
    @ResponseBody
    public List<Obj> getList(@RequestParam("supplierId") String supplierId, @RequestParam("paymentMethod") String paymentMethod) {
        InvestorFinancialInfo info = new InvestorFinancialInfo();
        Supplier supplier = new Supplier();
        supplier.setSupplierId(supplierId);
        info.setSupplier(supplier);
        info.setFinancingType("1");
        List<InvestorFinancialInfo> investorFinancialInfos = investorFinancialInfoService.findList(info);
        if(ObjectUtils.isEmpty(investorFinancialInfos)){
            return null;
        }
        InvestorFinancialInfo investorFinancialInfo = investorFinancialInfoService.get(investorFinancialInfos.get(0).getInvestorFinancialInfoId());
        List<Obj> list = new ArrayList<>();
        if ("3".equals(paymentMethod)) { // TT
            List<TtFinancialRatio> ttFinancialRatioList = investorFinancialInfo.getTtFinancialRatioList();
            for (TtFinancialRatio ttFinancialRatio : ttFinancialRatioList) {
                Obj result = new Obj();
                result.setId(ttFinancialRatio.getTtFinancialRatioId());
                result.setName(ttFinancialRatio.getOptionsName());
                list.add(result);
            }
        } else {
            List<LcFinancialRatio> lcFinancialRatioList = investorFinancialInfo.getLcFinancialRatioList();
            for (LcFinancialRatio lcFinancialRatio : lcFinancialRatioList) {
                Obj result = new Obj();
                result.setId(lcFinancialRatio.getLcFinancialRatioId());
                result.setName(lcFinancialRatio.getOptionsName());
                list.add(result);
            }
        }
        return list;
    }

    /**
     * 获取金融比例明细信息
     *
     * @param id
     */
    @RequestMapping(value = "getRatioInfo")
    @ResponseBody
    public Obj getRatioInfo(@RequestParam("id") String id, @RequestParam("paymentMethod") String paymentMethod) {
        Obj obj = new Obj();
        if ("3".equals(paymentMethod)) { // TT
            TtFinancialRatio ttFinancialRatio = new TtFinancialRatio();
            ttFinancialRatio.setTtFinancialRatioId(id);
            TtFinancialRatio entity = ttFinancialRatioDao.get(ttFinancialRatio);
            obj.setMarginRatio(entity.getMarginRatio());
            obj.setPrePayRatio(entity.getPrepaidExpenseRatio());
        } else {
            LcFinancialRatio lcFinancialRatio = new LcFinancialRatio();
            lcFinancialRatio.setLcFinancialRatioId(id);
            LcFinancialRatio entity = lcFinancialRatioDao.get(lcFinancialRatio);
            obj.setMarginRatio(entity.getMarginRatio());
            obj.setPrePayRatio(entity.getPrepaidExpenseRatio());
            obj.setNegotiatedRatioId(entity.getNegotiatedRatio());
        }
        return obj;
    }

    /**
     * 获取车辆信息
     *
     * @param carId
     */
    @RequestMapping(value = "getCarInfo")
    @ResponseBody
    public Tcar getCarInfo(@RequestParam("carId") String carId) {
        Tcar tcar = tcarService.get(carId);
        return tcar;
    }

    /**
     * 提交订单
     *
     * @param orderId
     */
    @RequestMapping(value = "submit")
    @ResponseBody
    public String submit(@RequestParam("orderId") String orderId) {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setServiceOrderId(orderId);
        serviceOrder.setOrderStatus("2");
        serviceOrder.setApproveStatus("2");
        serviceOrderService.update(serviceOrder);
        return renderResult(Global.TRUE, text("提交成功！"));
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @RequestMapping(value = "cancel")
    @ResponseBody
    public String cancel(@RequestParam("orderId") String orderId) {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setServiceOrderId(orderId);
        serviceOrder.setOrderStatus("4");
        serviceOrder.setApproveStatus("5");
        serviceOrderService.update(serviceOrder);
        return renderResult(Global.TRUE, text("取消成功！"));
    }

    /**
     * 更新版本
     *
     * @param orderId
     */
    @RequestMapping(value = "updateVersion")
    @ResponseBody
    @Transactional(readOnly = false)
    public String updateVersion(@RequestParam("orderId") String orderId) {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setServiceOrderId(orderId);
        ServiceOrder order = serviceOrderService.get(serviceOrder);
        ServiceOrder oldOrder = deepClone(order);
        oldOrder.setServiceOrderId("");
        oldOrder.setOrderStatus("6");
        for (ServiceOrderDetail serviceOrderDetail : oldOrder.getServiceOrderDetailList()) {
            serviceOrderDetail.setIsNewRecord(true);
            serviceOrderDetail.setServiceOrderDetailId("");
        }
        serviceOrderService.save(oldOrder);
        order.setVersion(order.getVersion() + 1);
        serviceOrderService.update(order);
        return renderResult(Global.TRUE, text("更新版本成功！"));
    }

    public static ServiceOrder deepClone(ServiceOrder object) {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(object);
            ByteArrayInputStream bais = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            ObjectInputStream objectInputStream = new ObjectInputStream(bais);
            return (ServiceOrder) objectInputStream.readObject();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 批单号录入
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:view")
    @RequestMapping(value = "lotNumberForm")
    public String lotNumber(ServiceOrder serviceOrder, Model model) {
        model.addAttribute("serviceOrder", serviceOrder);
        return "modules/order/serviceorder/lotNumberForm";
    }

    /**
     * 保存批单号
     */
    @RequiresPermissions("order:serviceorder:serviceOrder:edit")
    @PostMapping(value = "inputLotNumber")
    @ResponseBody
    @Transactional(readOnly = false)
    public String inputLotNumber(ServiceOrder serviceOrder) {
        serviceOrderService.save(serviceOrder);
        return renderResult(Global.TRUE, text("批单号保存成功！"));
    }

    /**
     * 生效订单
     *
     * @param orderId
     */
    @RequestMapping(value = "ok")
    @ResponseBody
    public String ok(@RequestParam("orderId") String orderId) {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setServiceOrderId(orderId);
        serviceOrder.setOrderStatus("3");
        serviceOrder.setApproveStatus("3");
        serviceOrderService.update(serviceOrder);
        return renderResult(Global.TRUE, text("生效成功！"));
    }

    /**
     * 拒绝订单
     *
     * @param orderId
     */
    @RequestMapping(value = "reject")
    @ResponseBody
    public String reject(@RequestParam("orderId") String orderId) {
        ServiceOrder serviceOrder = new ServiceOrder();
        serviceOrder.setServiceOrderId(orderId);
        serviceOrder.setOrderStatus("1");
        serviceOrder.setApproveStatus("4");
        serviceOrderService.update(serviceOrder);
        return renderResult(Global.TRUE, text("生效成功！"));
    }

    /**
     * 根据 资方和公司，获取车架号
     */
    @RequestMapping(value = "getFrameNumberByCondition")
    @ResponseBody
    public List<ServiceOrderDetail> getFrameNumberByCondition(@RequestParam("investorId") String investorId, @RequestParam("companyId") String companyId) {
        List<ServiceOrderDetail> list = serviceOrderService.getFrameNumberByCondition(investorId, companyId);
        ServiceOrderDetail serviceOrderDetail = new ServiceOrderDetail();
        serviceOrderDetail.setFrameNumber("");
        list.add(serviceOrderDetail);
        return list;
    }
    /**
     * 根据车架号 获取订单明细信息
     */
    @RequestMapping(value = "getOrderDetailByFrameNumber")
    @ResponseBody
    public ServiceOrderDetail getOrderDetailByFrameNumber(@RequestParam("frameNumber") String frameNumber) {
        return serviceOrderService.getOrderDetailByFrameNumber(frameNumber);
    }

    /**
     * 根据车架号 获取订单明细信息
     */
    @RequestMapping(value = "getOrderDetailByFrame")
    @ResponseBody
    public ServiceOrderDetail getOrderDetailByFrame(@RequestParam("frameNumber") String frameNumber) {
        return serviceOrderService.getOrderDetailByFrame(frameNumber);
    }

    /**
     * 保证金预收支按钮
     */
    @PostMapping(value = "goBZJ")
    @ResponseBody
    @Transactional(readOnly=false)
    public String goBZJ(@RequestParam("serviceOrderId") String serviceOrderId) {
        ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
        if(StringUtils.isEmpty(serviceOrder.getBzjYusId())){
            // 生成预收
            TadvancesReceived tadvancesReceived = new TadvancesReceived();
            tadvancesReceived.setCustomerId(serviceOrder.getCustomer().getCustomerId());
            tadvancesReceived.setDate(new Date());
            tadvancesReceived.setStatus1("1");
            tadvancesReceived.setBillStatus("2");// 已提交
            tadvancesReceived.setServiceOrderId(serviceOrderId);
            tadvancesReceived.setCurrency(serviceOrder.getCurrency());
            tadvancesReceived.setParentBillType("ServiceOrder");
            tadvancesReceived.setParentBillCode(serviceOrderId);
            Double total = 0D;
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                TadvancesReceivedEstimated tadvancesReceivedEstimated = new TadvancesReceivedEstimated();
                tadvancesReceivedEstimated.setFrameNumber(serviceOrderDetail.getFrameNumber());
                tadvancesReceivedEstimated.setAdvancesReceivedType(AccountType.KZBZJ.getCode());//"ITM00000001");
                tadvancesReceivedEstimated.setEstimatedReceivedAmount(serviceOrderDetail.getRiskMargin());
                tadvancesReceivedEstimated.setReceivedAmountActual(0D);
                tadvancesReceivedEstimated.setReceivedAmountEstimated(serviceOrderDetail.getRiskMargin());
                tadvancesReceivedEstimated.setRowNumber(serviceOrderDetail.getRowNumber());
                tadvancesReceivedEstimated.setCarName1(serviceOrderDetail.getTcar().getCarName());
                tadvancesReceived.getTadvancesReceivedEstimatedList().add(tadvancesReceivedEstimated);
                total = NumberUtils.add(total,serviceOrderDetail.getRiskMargin());
            }
            tadvancesReceived.setEstimatedReceivedAmount(total);
            tadvancesReceivedService.save(tadvancesReceived);
            ServiceOrder order = new ServiceOrder();
            order.setServiceOrderId(serviceOrderId);
            order.setBzjYusId(tadvancesReceived.getAdvancesReceivedId());
            serviceOrderService.update(order);
        }

        if(StringUtils.isEmpty(serviceOrder.getBzjYufId())){
            //生成预付
            Tprepayment tprepayment = new Tprepayment();
            tprepayment.setSupplierId(serviceOrder.getInvestorId());
            tprepayment.setDate(new Date());
            tprepayment.setStatus1("1");
            tprepayment.setServiceOrderId(serviceOrderId);
            tprepayment.setCurrency(serviceOrder.getCurrency());
            tprepayment.setBillStatus("2");// 已提交
            tprepayment.setParentBillType("ServiceOrder");
            tprepayment.setParentBillCode(serviceOrderId);
            Double total = 0D;
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                TprepaymentEstimated tprepaymentEstimated = new TprepaymentEstimated();
                tprepaymentEstimated.setFrameNumber(serviceOrderDetail.getFrameNumber());
                tprepaymentEstimated.setPrepaymentType(AccountType.KZBZJ.getCode());//"ITM00000001");
                tprepaymentEstimated.setEstimatedPaymentAmount(serviceOrderDetail.getRiskMargin1());
                tprepaymentEstimated.setPaymentAmountActual(0D);
                tprepaymentEstimated.setPaymentAmountEstimated(serviceOrderDetail.getRiskMargin1());
                tprepaymentEstimated.setRowNumber(serviceOrderDetail.getRowNumber());
                tprepaymentEstimated.setCarName(serviceOrderDetail.getTcar().getCarName());
                tprepayment.getTprepaymentEstimatedList().add(tprepaymentEstimated);
                total = NumberUtils.add(total,serviceOrderDetail.getRiskMargin1());
            }
            tprepayment.setEstimatedPaymentAmount(total);
            tprepaymentService.save(tprepayment);
            ServiceOrder order1 = new ServiceOrder();
            order1.setServiceOrderId(serviceOrderId);
            order1.setBzjYufId(tprepayment.getPrepaymentId());
            serviceOrderService.update(order1);
        }

        return renderResult(Global.TRUE, text("生成成功！"));
    }

    /**
     * 预收费用按钮
     */
    @PostMapping(value = "goYS")
    @ResponseBody
    @Transactional(readOnly=false)
    public String goYS(@RequestParam("serviceOrderId") String serviceOrderId) {
        ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
        // 生成预收
        TadvancesReceived tadvancesReceived = new TadvancesReceived();
        tadvancesReceived.setCustomerId(serviceOrder.getCustomer().getCustomerId());
        tadvancesReceived.setDate(new Date());
        tadvancesReceived.setStatus1("1");
        tadvancesReceived.setServiceOrderId(serviceOrderId);
        tadvancesReceived.setCurrency(serviceOrder.getCurrency());
        tadvancesReceived.setBillStatus("2");// 已提交
        tadvancesReceived.setParentBillType("ServiceOrder");
        tadvancesReceived.setParentBillCode(serviceOrderId);
        Double total = 0D;
        for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
            TadvancesReceivedEstimated tadvancesReceivedEstimated = new TadvancesReceivedEstimated();
            tadvancesReceivedEstimated.setFrameNumber(serviceOrderDetail.getFrameNumber());
            tadvancesReceivedEstimated.setAdvancesReceivedType(AccountType.KZYSF.getCode());//"ITM00000003");
            tadvancesReceivedEstimated.setEstimatedReceivedAmount(serviceOrderDetail.getPrePay());
            tadvancesReceivedEstimated.setReceivedAmountActual(0D);
            tadvancesReceivedEstimated.setReceivedAmountEstimated(serviceOrderDetail.getPrePay());
            tadvancesReceivedEstimated.setRowNumber(serviceOrderDetail.getRowNumber());
            tadvancesReceivedEstimated.setCarName1(serviceOrderDetail.getTcar().getCarName());
            tadvancesReceived.getTadvancesReceivedEstimatedList().add(tadvancesReceivedEstimated);
            total = NumberUtils.add(total,serviceOrderDetail.getPrePay());
        }
        tadvancesReceived.setEstimatedReceivedAmount(total);
        tadvancesReceivedService.save(tadvancesReceived);
        ServiceOrder order = new ServiceOrder();
        order.setServiceOrderId(serviceOrderId);
        order.setYsfyId(tadvancesReceived.getAdvancesReceivedId());
        serviceOrderService.update(order);
        return renderResult(Global.TRUE, text("生成成功！"));
    }

    /**
     * 获取代理费信息
     *
     * @param investorId
     * @param amount
     */
    @RequestMapping(value = "getAgencyFee")
    @ResponseBody
    public LadderPrice getAgencyFee(@RequestParam("investorId") String investorId, @RequestParam("amount") Double amount) {
        LadderPrice ladderPrice = new LadderPrice();
        FixedExpense fixedExpense = fixedExpenseService.get(AccountType.KZDLF.getCode());//"ITM00000004");
        List<LadderPrice> collect = fixedExpense.getLadderPriceList().stream().filter(i -> investorId.equals(i.getInvestorId())
                && amount >= i.getStartAmount() && amount <= i.getEndAmount()).collect(Collectors.toList());
        if(ListUtils.isNotEmpty(collect)){
            ladderPrice = collect.get(0);
        } else {
            ladderPrice.setSalesPrice(0D);
            ladderPrice.setPurchasePrice(0D);
        }
        return ladderPrice;
    }

    /**
     * 代理费预收支按钮
     */
    @PostMapping(value = "goDLFYSZ")
    @ResponseBody
    @Transactional(readOnly=false)
    public String goDLFYSZ(@RequestParam("serviceOrderId") String serviceOrderId) {
        ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
        if(StringUtils.isEmpty(serviceOrder.getDlfYusId())){
            // 生成预收
            TadvancesReceived tadvancesReceived = new TadvancesReceived();
            tadvancesReceived.setCustomerId(serviceOrder.getCustomer().getCustomerId());
            tadvancesReceived.setDate(new Date());
            tadvancesReceived.setStatus1("1");
            tadvancesReceived.setServiceOrderId(serviceOrderId);
            tadvancesReceived.setCurrency(serviceOrder.getCurrency());
            tadvancesReceived.setBillStatus("2");// 已提交
            tadvancesReceived.setParentBillType("ServiceOrder");
            tadvancesReceived.setParentBillCode(serviceOrderId);
            Double total = 0D;
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                TadvancesReceivedEstimated tadvancesReceivedEstimated = new TadvancesReceivedEstimated();
                tadvancesReceivedEstimated.setFrameNumber(serviceOrderDetail.getFrameNumber());
                tadvancesReceivedEstimated.setAdvancesReceivedType(AccountType.KZDLF.getCode());//"ITM00000004");
                tadvancesReceivedEstimated.setEstimatedReceivedAmount(serviceOrderDetail.getAgencyFee());
                tadvancesReceivedEstimated.setReceivedAmountActual(0D);
                //tadvancesReceivedEstimated.setReceivedAmountEstimated(serviceOrderDetail.getAgencyFee());
                tadvancesReceivedEstimated.setRowNumber(serviceOrderDetail.getRowNumber());
                tadvancesReceivedEstimated.setCarName1(serviceOrderDetail.getTcar().getCarName());
                tadvancesReceived.getTadvancesReceivedEstimatedList().add(tadvancesReceivedEstimated);
                total = NumberUtils.add(total,serviceOrderDetail.getAgencyFee());
            }
            tadvancesReceived.setEstimatedReceivedAmount(total);
            tadvancesReceivedService.save(tadvancesReceived);
            ServiceOrder order = new ServiceOrder();
            order.setServiceOrderId(serviceOrderId);
            order.setDlfYusId(tadvancesReceived.getAdvancesReceivedId());
            serviceOrderService.update(order);
        }

        if(StringUtils.isEmpty(serviceOrder.getDlfYufId())){
            //生成预付
            Tprepayment tprepayment = new Tprepayment();
            tprepayment.setSupplierId(serviceOrder.getInvestorId());
            tprepayment.setDate(new Date());
            tprepayment.setStatus1("1");
            tprepayment.setServiceOrderId(serviceOrderId);
            tprepayment.setCurrency(serviceOrder.getCurrency());
            tprepayment.setBillStatus("2");// 已提交
            tprepayment.setParentBillType("ServiceOrder");
            tprepayment.setParentBillCode(serviceOrderId);
            Double total = 0D;
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                TprepaymentEstimated tprepaymentEstimated = new TprepaymentEstimated();
                tprepaymentEstimated.setFrameNumber(serviceOrderDetail.getFrameNumber());
                tprepaymentEstimated.setPrepaymentType(AccountType.KZDLF.getCode());//"ITM00000004");
                tprepaymentEstimated.setEstimatedPaymentAmount(serviceOrderDetail.getAgencyFee1());
                tprepaymentEstimated.setPaymentAmountActual(0D);
                //tprepaymentEstimated.setPaymentAmountEstimated(serviceOrderDetail.getAgencyFee1());
                tprepaymentEstimated.setRowNumber(serviceOrderDetail.getRowNumber());
                tprepaymentEstimated.setCarName(serviceOrderDetail.getTcar().getCarName());
                tprepayment.getTprepaymentEstimatedList().add(tprepaymentEstimated);
                total = NumberUtils.add(total,serviceOrderDetail.getAgencyFee1());
            }
            tprepayment.setEstimatedPaymentAmount(total);
            tprepaymentService.save(tprepayment);
            ServiceOrder order1 = new ServiceOrder();
            order1.setServiceOrderId(serviceOrderId);
            order1.setDlfYufId(tprepayment.getPrepaymentId());
            serviceOrderService.update(order1);
        }

        return renderResult(Global.TRUE, text("生成成功！"));
    }

    /**
     * 代理费收支按钮
     */
    @PostMapping(value = "goDLFSZ")
    @ResponseBody
    @Transactional(readOnly=false)
    public String goDLFSZ(@RequestParam("serviceOrderId") String serviceOrderId) {
        ServiceOrder serviceOrder = serviceOrderService.get(serviceOrderId);
        if(StringUtils.isEmpty(serviceOrder.getDlfYisId())){
            // 生成应收
            Tar ar = new Tar();
            ar.setCustomer(serviceOrder.getCustomer());
            ar.setCustomerId(serviceOrder.getCustomer().getCustomerId());
            ar.setDate(new Date());
            ar.setStatus1("1");
            ar.setBillStatus("2");// 已提交
            ar.setServiceOrderId(serviceOrder.getServiceOrderId());
            ar.setCurrency(serviceOrder.getCurrency());
            ar.setParentBillType("ServiceOrder");
            ar.setParentBillCode(serviceOrder.getServiceOrderId());
            Double total = 0D;
            List<TarDetail> list = ListUtils.newArrayList();
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                TarDetail detail = new TarDetail();
                detail.setCarId(serviceOrderDetail.getCarId());
                detail.setFrameNumber(serviceOrderDetail.getFrameNumber());
                detail.setModel(serviceOrderDetail.getModel());
                detail.setExpenseItem(AccountType.KZDLF.getCode());//"ITM00000004");
                detail.setApAmount(serviceOrderDetail.getAgencyFee());
                total = NumberUtils.add(total, serviceOrderDetail.getAgencyFee());
                detail.setBrand(serviceOrderDetail.getBrand());
                detail.setArea(serviceOrderDetail.getArea());
                detail.setRowNumber(serviceOrderDetail.getRowNumber());
                list.add(detail);
            }
            ar.setAmount(total);
            ar.setTarDetailList(list);
            tarService.save(ar);
            ServiceOrder order = new ServiceOrder();
            order.setServiceOrderId(serviceOrderId);
            order.setDlfYisId(ar.getArId());
            serviceOrderService.update(order);
        }

        if(StringUtils.isEmpty(serviceOrder.getDlfYifId())){
            //生成应付
            Tap ap = new Tap();
            ap.setSupplierId(serviceOrder.getInvestorId());
            ap.setDate(new Date());
            ap.setStatus1("1");
            ap.setBillStatus("2");// 已提交
            ap.setServiceOrderId(serviceOrder.getServiceOrderId());
            ap.setCurrency(serviceOrder.getCurrency());
            ap.setParentBillType("ServiceOrder");
            ap.setParentBillCode(serviceOrder.getServiceOrderId());
            Double total = 0D;
            List<TapDetail> list = ListUtils.newArrayList();
            for (ServiceOrderDetail serviceOrderDetail : serviceOrder.getServiceOrderDetailList()) {
                TapDetail detail = new TapDetail();
                detail.setCarId(serviceOrderDetail.getCarId());
                detail.setFrameNumber(serviceOrderDetail.getFrameNumber());
                detail.setModel(serviceOrderDetail.getModel());
                detail.setExpenseItem(AccountType.KZDLF.getCode());//"ITM00000004");
                detail.setApAmount(serviceOrderDetail.getAgencyFee1());
                total = NumberUtils.add(total, serviceOrderDetail.getAgencyFee1());
                detail.setBrand(serviceOrderDetail.getBrand());
                detail.setArea(serviceOrderDetail.getArea());
                detail.setRowNumber(serviceOrderDetail.getRowNumber());
                list.add(detail);
            }
            ap.setTapDetailList(list);
            ap.setAmount(total);
            tapService.save(ap);
            ServiceOrder order1 = new ServiceOrder();
            order1.setServiceOrderId(serviceOrderId);
            order1.setDlfYifId(ap.getApId());
            serviceOrderService.update(order1);
        }

        return renderResult(Global.TRUE, text("生成成功！"));
    }

    class Obj {
        private String id;
        private String name;
        private String marginRatio;
        private String negotiatedRatioId;
        private String prePayRatio;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getMarginRatio() {
            return marginRatio;
        }

        public void setMarginRatio(String marginRatio) {
            this.marginRatio = marginRatio;
        }

        public String getNegotiatedRatioId() {
            return negotiatedRatioId;
        }

        public void setNegotiatedRatioId(String negotiatedRatioId) {
            this.negotiatedRatioId = negotiatedRatioId;
        }

        public String getPrePayRatio() {
            return prePayRatio;
        }

        public void setPrePayRatio(String prePayRatio) {
            this.prePayRatio = prePayRatio;
        }
    }

}
